/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package common;

import java.io.*;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xml.sax.InputSource;


/*
 * This file is part of shared-drawing.
 * shared-drawing is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option )
 * any later version. shared-drawing is distributed in the hope that it will
 * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 * You should have received a copy of the GNU General Public License along with 
 * shared-drawing. If not, seehttp://www.gnu.org/licenses/.
 */

public class StreamToInput {
    
    private static StreamToInput instance = null;
    
    private LinkedList<String> queue;
    
    public StreamToInput()
    {
        queue = new LinkedList();
    }
    
    public InputSource transform(InputStream stream){
        String s=""; //the string that will be sent
        char c; //the first character
        if(queue.isEmpty())
        {
            try {
                c = (char)stream.read();//used to block until the stream is not empty
                if(c != '<')
                {
                    return null;
                }
            } catch (IOException ex) {
                return null;
            }
            s +=c;//put back the first character
            BufferedReader receiving = new BufferedReader( new InputStreamReader(stream));
            try {
                while(receiving.ready())
                {
                    String line = receiving.readLine();//get a line
                    if(line == null)//the stream has been closed
                    {
                        return null;
                    }
                    if(line.charAt(1) == '?')
                    {
                        queue.add(s);
                        s = "";
                    }
                    s += line;
                }
                queue.add(s);
                
            } catch (IOException ex) {
                System.out.println("transformer read exception");
                Logger.getLogger(StreamToInput.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }
        }
        if ( !queue.getFirst().isEmpty() )
        {
            System.out.println("receiving : " + queue.getFirst());
            return new InputSource(new StringReader(queue.removeFirst()));//and return it
        }
        else
            return null;
    }
}
